package me.nereo.multi_image_selector;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ali.music.multi_image_selector.R;
import com.bumptech.glide.Glide;

import java.util.ArrayList;

import me.nereo.multi_image_selector.view.DefaultOnDoubleTapListener;
import me.nereo.multi_image_selector.view.HackyViewPager;
import me.nereo.multi_image_selector.view.PhotoView;
import me.nereo.multi_image_selector.view.PhotoViewAttacher;

/**
 * Created by yuanxiaowei on 15/10/22.
 */
public class MultiImagePreviewFragment extends Fragment implements View.OnClickListener {
    /**
     * 只预览图片
     */
    public static final int MODE_PREVIEW = 0;
    /**
     * 预览、选择图片
     */
    public static final int MODE_CHOOSE = 1;
    /**
     * 预览、存储图片
     */
    public static final int MODE_SAVE = 2;
    private int mCurMode = MODE_PREVIEW;
    private static final int INVALID_ID = -1;

    /* 被选中列表*/
    private ArrayList<String> mListResult;
    /**
     * 预览列表
     */
    private ArrayList<String> mListPreview;
    /**
     * 可选择总数
     */
    private int mSelectCount;
    /**
     * 当前显示第几张
     */
    private int mSelectedPosition;
    /**
     * 是否存储
     */
    private boolean mCanSave;
    /**
     * 存储路劲
     */
    private String mSavePath;

    //view
    private HackyViewPager mViewPager;
    private PreviewPagerAdapter mPAPreview;

    //toolbar
    private View mLayoutToolbar;
    private ImageView mIVBack;
    private Button mBTSubmit;
    private Button mBTCategory;
    //状态
    private ImageView mIVSelectView;
    private TextView mTVSaveView;
    private TextView mTVSaveNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.multi_fragment_preview, container, false);
    }

    /**
     * @param view               View
     * @param savedInstanceState private
     */
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        mListResult = bundle.getStringArrayList(PrivateContent.EXTRA_DEFAULT_SELECTED_LIST);
        mListPreview = bundle.getStringArrayList(PrivateContent.EXTRA_PREVIEW_SELECTED_LIST);
        mSelectCount = bundle.getInt(PrivateContent.EXTRA_SELECT_COUNT, 0);
        mSelectedPosition = bundle.getInt(PrivateContent.EXTRA_SELECTED_POSITION, 0);
        mCanSave = bundle.getBoolean(PrivateContent.EXTRA_CAN_SAVE, false);
        mSavePath = bundle.getString(PrivateContent.EXTRA_SAVE_PATH, "");
        mCurMode = bundle.getInt(PrivateContent.EXTRA_MODE, MODE_PREVIEW);
        if (mSelectedPosition >= mListPreview.size() || mSelectedPosition < 0) {
            mSelectedPosition = 0;
        }

        iniToolbar(view);
        mViewPager = (HackyViewPager) view.findViewById(R.id.vp_preview_list);
        mPAPreview = new PreviewPagerAdapter();
        mViewPager.setAdapter(mPAPreview);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                refrashCurNum(position);
                if (mCurMode == MODE_CHOOSE) {
                    String url = mListPreview.get(position);
                    refrashChooseState(url);
                    refrashSubmit();
                }
            }
        });
    }

    private void iniToolbar(View view) {
        mLayoutToolbar = view.findViewById(R.id.toolbar);
        // 返回按钮
        mIVBack = (ImageView) view.findViewById(R.id.btn_back);
        mIVBack.setOnClickListener(this);
        mBTSubmit = (Button) view.findViewById(R.id.commit);
        refrashSubmit();
        mBTSubmit.setOnClickListener(this);
        mBTCategory = (Button) view.findViewById(R.id.category_btn);
        mBTCategory.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        mBTCategory.setEnabled(false);
        //界面浮层
        mIVSelectView = (ImageView) view.findViewById(R.id.cb_photo_lpsi);
        mTVSaveView = (TextView) view.findViewById(R.id.mult_save);
        mTVSaveNum = (TextView) view.findViewById(R.id.mult_save_num);
        mIVSelectView.setOnClickListener(this);
        mTVSaveView.setOnClickListener(this);


        switch (mCurMode) {
            case MODE_PREVIEW:
                mLayoutToolbar.setVisibility(View.GONE);
                mIVSelectView.setVisibility(View.GONE);
                mTVSaveView.setVisibility(View.GONE);
                break;
            case MODE_CHOOSE:
                mIVSelectView.setVisibility(View.VISIBLE);
                if (mListResult == null) {
                    mListResult = new ArrayList<>(mListPreview.size());
                }
                mTVSaveView.setVisibility(View.GONE);

                String url = mListPreview.get(mSelectedPosition);
                refrashCurNum(mSelectedPosition);
                refrashChooseState(url);
                refrashSubmit();
                break;
            case MODE_SAVE:
                if (mListResult == null) {
                    mListResult = new ArrayList<>(mListPreview.size());
                }
                mLayoutToolbar.setVisibility(View.GONE);
                mIVSelectView.setVisibility(View.GONE);
                mTVSaveView.setVisibility(View.VISIBLE);
                mTVSaveNum.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void refrashCurNum(int position) {
        if (mCurMode == MODE_PREVIEW) {
            return;
        }
        String num = (position + 1) + " / " + mListPreview.size();
        mBTCategory.setText(num);
        mTVSaveNum.setText(num);
    }

    private void refrashChooseState(String url) {
        //当前选中状态
        if (mListResult.contains(url)) {
            mIVSelectView.setImageResource(R.drawable.multi_default_check_s);
        } else {
            mIVSelectView.setImageBitmap(null);
        }
    }

    private void refrashSubmit() {
        if (mListResult == null || mListResult.size() <= 0) {
            mBTSubmit.setText(R.string.multi_next);
            mBTSubmit.setEnabled(false);
        } else {
            mBTSubmit.setText(getString(R.string.multi_next_num, mListResult.size(), mSelectCount));
            mBTSubmit.setEnabled(true);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mViewPager.setCurrentItem(mSelectedPosition);
    }

    /**
     * @return true this remove self
     */
    public boolean onBackPressed() {
        Intent data = new Intent();
        data.putExtra(PrivateContent.EXTRA_EXIT, true);
        data.putStringArrayListExtra(MultiContent.EXTRA_RESULT, mListResult);
        getActivity().setResult(Activity.RESULT_OK, data);
        getActivity().finish();
        return true;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_back) {
            onBackPressed();
        } else if (id == R.id.commit) {
            // 返回已选择的图片数据
            Intent data = new Intent();
            data.putStringArrayListExtra(MultiContent.EXTRA_RESULT, mListResult);
            getActivity().setResult(Activity.RESULT_OK, data);
            getActivity().finish();
        } else if (id == R.id.cb_photo_lpsi) {
            //选择
            int position = mViewPager.getCurrentItem();
            String url = mListPreview.get(position);
            if (mListResult.contains(url)) {
                mListResult.remove(url);
            } else if (mListResult.size() >= mSelectCount) {
                Toast.makeText(getActivity(), R.string.multi_msg_amount_limit, Toast.LENGTH_SHORT).show();
                return;
            } else {
                mListResult.add(url);
            }
            refrashCurNum(position);
            refrashChooseState(url);
            refrashSubmit();
        } else if (id == R.id.mult_save) {
            int position = mViewPager.getCurrentItem();
            saveImage(position);
        }
    }

    private void saveImage(int position) {
//        String url = mListPreview.get(position);
//
//        File file = FileUtils.getDownloadFile(getActivity(), url);
//        if(file.exists()){
//            ToastUtils.showToast(getString(R.string.multi__save_haved));
//            return;
//        }
    }

    class PreviewPagerAdapter extends PagerAdapter {
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            if (mCurMode == MODE_PREVIEW || mCurMode == MODE_SAVE) {
                PhotoViewAttacher mAttacher = new PhotoViewAttacher(photoView);
                photoView.setTag(R.id.mult_save, mAttacher);
                OnDoubleTapListener mOnDoubleTapListener = new OnDoubleTapListener(mAttacher);
                mAttacher.setOnDoubleTapListener(mOnDoubleTapListener);
            }

            Glide.with(MultiImagePreviewFragment.this)
                    .load(mListPreview.get(position))
                    .into(photoView);
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            PhotoView mPhotoView = (PhotoView) object;
            PhotoViewAttacher mAttacher = (PhotoViewAttacher) mPhotoView.getTag(R.id.mult_save);
            mPhotoView.setTag(R.id.mult_save, null);
            if (mAttacher != null) {
                mAttacher.cleanup();
            }
            container.removeView(mPhotoView);
        }

        @Override
        public int getCount() {
            return mListPreview.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    private class OnDoubleTapListener extends DefaultOnDoubleTapListener {
        public OnDoubleTapListener(PhotoViewAttacher photoViewAttacher) {
            super(photoViewAttacher);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            onBackPressed();
            return true;

        }

    }
}
